const Utils = require('../../../utils'); // 工具函数
const LinkInfoArticleTalk = require('../../../models/blog_article_talk');

const ControllerArticleTalk = {
    /* 获取列表 */
    getList: async function (req, res, next) {
        try {
            const { article_id, per_page, page } = req.query;
            let all;

            if (article_id) {
                all = await LinkInfoArticleTalk.select({ article_id })
            } else {
                all = await LinkInfoArticleTalk.all()
            }
            const getComment = Utils.getData(all); //* 树形数据处理索引0为一级，其他均为子级
            const commentData = Utils.getChildrenTree(getComment, getComment[0]); //* 按父子关系处理分类
            const list = Utils.getPagination(commentData, per_page, page);

            list.sort((a, b) => {
                return a.id - b.id
            })

            res.json({ code: 200, msg: '获得列表', data: { list, total: all.length } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 获取详情 */
    getById: async function (req, res, next) {
        try {
            const { id } = req.query;
            const list = await LinkInfoArticleTalk.select({ id });
            list[0].content = decodeURI(list[0].content);
            list[0].reply_content = decodeURI(list[0].reply_content);

            res.json({ code: 200, msg: '获得列表', data: { list: list[0] } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 新增/回复 */
    Insert: async function (req, res, next) {
        try {
            const { id, article_id, content } = req.body;
            const item = await LinkInfoArticleTalk.select({ id })
            let params = { article_id, content: encodeURI(content), name: '闲云野鹤', master: 1, created_time: new Date().getTime() };
            params.pid = item[0].pid ? item[0].pid : id;
            params.reply_id = id;
            params.reply_name = item[0].name;
            params.reply_content = item[0].content;
            params.reply_master = item[0].master;

            await LinkInfoArticleTalk.insert(params);

            res.json({ code: 200, msg: '留言成功', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    /* 删除 */
    del: async function (req, res, next) {
        try {
            const { id } = req.body;
            let ids = [id];
            if (typeof (id) === 'string') ids = id.split(',');

            await LinkInfoArticleTalk.batchDel(ids);

            res.json({ code: 200, msg: '删除成功', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    }
}

module.exports = ControllerArticleTalk;